package main

import (
	"context"
	"flag"
	"fmt"
	"gog/grpc-test/helloworld"
	"google.golang.org/grpc"
	"log"
	"net"
	"net/http"
	"strings"
)

var (
	port = flag.Int("port", 50051, "The server port")
)

type server struct {
	helloworld.UnimplementedGreeterServer
}

func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) {
	log.Printf("Received: %v", in.GetName())
	return &helloworld.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func main() {

	// 纯grpc调用
	flag.Parse()
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	s := grpc.NewServer()
	helloworld.RegisterGreeterServer(s, &server{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}

	// gateway调用
	//ctx := context.Background()
	//mux := http.NewServeMux()
	//muxgw := runtime.NewServeMux()
	//helloworld.RegisterGreeterHandlerServer(ctx, muxgw, &server{})
	//mux.Handle("/", muxgw)
	//mux.HandleFunc("/swagger-json", func(writer http.ResponseWriter, request *http.Request) {
	//	file, err := os.ReadFile("D:\\workspaces\\gog\\grpc-test\\helloworld.swagger.json")
	//	if err != nil {
	//		return
	//	}
	//	writer.Write(file)
	//})
	//mux.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
	//	writer.Write([]byte("fewafa"))
	//},
	//)
	//mux.Handle("/f", http.FileServer(http.Dir("D:\\workspaces\\gog\\grpc-test\\dist")))
	//mux.HandleFunc("/swagger", func(writer http.ResponseWriter, request *http.Request) {
	//	file, err := os.ReadFile("D:\\workspaces\\gog\\grpc-test\\dist\\index.html")
	//	if err != nil {
	//		return
	//	}
	//	writer.Write(file)
	//})
	//fmt.Println("开始监听")
	//http.ListenAndServe("localhost:8090", allowCORS(mux))

	// swagger调用

}

func allowCORS(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if origin := r.Header.Get("Origin"); origin != "" {
			w.Header().Set("Access-Control-Allow-Origin", origin)
			if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
				preflightHandler(w, r)
				return
			}
		}
		h.ServeHTTP(w, r)
	})
}

func preflightHandler(w http.ResponseWriter, r *http.Request) {
	headers := []string{"Content-Type", "Accept", "Authorization"}
	w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
	methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
	w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
	//log.Infof("preflight request for %s", r.URL.Path)
}
